<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-button size="small" type="primary" @click="batchDialogState = true">批量绑定</el-button>
					<!--<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>-->
					<!--<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" placeholder="区域" size="small" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.groupId" :option-list="groupList" placeholder="班组" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.postName" placeholder="岗位名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.nameOrCode" placeholder="员工编号或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" border :span-method="mergeColMethod" :loading="tableLoading" :data="tableData" :height="tableHeight + 20">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<div v-if="item.keyName === 'name'" class="emp-total-machine-count">
							<div>
								<el-button class="emp-name-btn" type="default" size="small" @click="onSetMachine(scope)">{{ scope.row.name }}</el-button>
								<span style="color: #808695;font-size: 12px;">{{ `(${scope.row.empMachineList ? scope.row.empMachineList.length : '0'}台)` }}</span>
							</div>
						</div>
						<div v-else-if="item.keyName === 'empMachineList'" class="flex-start-center-wrap">
							<el-tag
								v-for="machineItem in scope.row.empMachineList"
								:key="machineItem.machineId"
								class="emp-machine-item"
								type="info"
							>{{ machineItem.machineName }}</el-tag>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<!--<vxe-column title="操作" align="center" fixed="right" :width="120">
					<template slot-scope="scope">
						<el-button type="primary" size="mini" @click="onSetMachine(scope)">分配</el-button>
					</template>
				</vxe-column>-->
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<detail-dialog
			:data-id="dataId"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detail-dialog>
		<save-dialog
			:permission-prefix="prefix"
			:emp-item="selectedEmp"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
		<batch-dialog
			:permission-prefix="prefix"
			:dialog-state="batchDialogState"
			@on-visible-change="onBatchDialogVisibleChange"
			@on-finish="onBatchDialogFinish"
		></batch-dialog>
	</div>
</template>

<script>
    import saveDialog from './save-dialog';
    import batchDialog from './batch-dialog';
    import detailDialog from './detail-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig } from '/src/utils/jk/jk-tool';
    import {
        workforcemanagementEmpMachinePage,
        workforcemanagementEmpMachineDelete,
        workforcemanagementEmpMachineExportExcel
    } from '../../../api/schedule/empMachine';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { personnelGroupPage } from '../../../api/personnel/group';

    export default {
        name: 'EmpMachine',
        components: {
            saveDialog,
            detailDialog,
            batchDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                prefix: 'workforcemanagement:empMachine',
                apiItem: {
                    'page': workforcemanagementEmpMachinePage,
                    'exportExcel': workforcemanagementEmpMachineExportExcel,
                    'delete': workforcemanagementEmpMachineDelete
                },
                batchDialogState: false,
                selectedEmp: {},
                workshopList: [],
                groupList: [],
                detailDialogState: false,
                dataId: null,
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    workshopId: null,
                    groupId: null,
                    postName: '挡车工',
                    nameOrCode: ''
                }
            };
        },
        methods: {
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onBatchDialogFinish() {
                this.batchDialogState = false;
                this.getListRequest();
            },
            onBatchDialogVisibleChange(e) {
                this.batchDialogState = e;
            },
            onSetMachine(scope) {
                this.selectedEmp = scope.row;
                this.saveDialogState = true;
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['typeName']; // 根据字段判断数据相同的合并
                const cellValue = row[column.property];
                if (cellValue && fields.includes(column.property)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.property] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.property] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onDetailBtn(e) {
                this.dataId = e.id;
                this.detailDialogState = true;
            },
            onVisibleChangeOfDetailDialog(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.detailDialogState = e;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.saveDialogState = e;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.apiItem.page(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            getGroupListRequest() {
                if (!this.searchParams.workshopId) return;
                return personnelGroupPage({ auditState: 1, workshopId: this.searchParams.workshopId }).then(res => {
                    if (res.data.status === 200) {
                        this.groupList = res.data.res;
                        this.getListRequest();
                    }
                });
            },
            onWorkshopChange() {
                this.searchParams.groupId = null;
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getGroupListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.saveDialogState = true;
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.saveDialogState = true;
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有人机绑定数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem.exportExcel(params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                this.groupList = this.$store.state.user.userGroup.groupList;
                // this.$set(this.searchParams, 'groupId', this.$store.state.user.userGroup.defaultGroupId);
                await this.getMenuColumnListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style scoped lang="scss">
    .emp-name-btn {
        width: 120px;
        font-size: 14px;
        color: #2b85e4;
        white-space: nowrap;
        overflow:hidden;
        text-overflow: ellipsis;
    }
    .emp-total-machine-count {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        font-size: 12px;
    }
    .emp-machine-item {
        width: 100px;
        margin: 1px;
        display: flex;
        justify-content: center;
        align-content: center;
    }
</style>
